package com.fc.v2.service.auto.impl;

import cn.hutool.core.text.StrSplitter;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.fc.v2.mapper.auto.SysRoleMapper;
import com.fc.v2.model.auto.SysRole;
import com.fc.v2.model.auto.SysRoleUser;
import com.fc.v2.model.auto.SysUser;
import com.fc.v2.service.auto.ISysRoleService;
import com.fc.v2.service.auto.ISysRoleUserService;
import com.fc.v2.service.auto.SysUserService;
import com.fc.v2.util.SnowflakeIdWorker;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 * 用户角色表 服务实现类
 * </p>
 *
 * @author v2
 * @since 2022-01-22
 */
@Service
public class SysRoleServiceImpl extends ServiceImpl<SysRoleMapper, SysRole> implements ISysRoleService {
    @Resource
    private  SysUserService sysUserService;
    @Resource
    private ISysRoleUserService iSysRoleUserService;


    /**
     * 用户id绑定角色
     * @params [userId, roles]
     * @returns boolean
     * @Date 2022/1/26 11:03
     * @Created by 87766867@qq.com
     */
    @Override
    public boolean userOnboundRole(String userId, String roles) {
        SysUser sysUser= sysUserService.selectByPrimaryKey(userId);
        List<String> roles_list=StrSplitter.split(roles,",",true,true);
        if(sysUser!=null&&roles_list!=null&&roles_list.size()>0){
            //先删除后增加
            LambdaQueryWrapper<SysRoleUser> lambdaQueryWrapper= new LambdaQueryWrapper<SysRoleUser>();
            lambdaQueryWrapper.eq(SysRoleUser::getSysUserId,userId);
            iSysRoleUserService.remove(lambdaQueryWrapper);

            //新增
            List<SysRoleUser> sysRoleUsers=new ArrayList<>();
            roles_list.forEach(item->{
                SysRoleUser sysRoleUser=new SysRoleUser(SnowflakeIdWorker.getUUID(),sysUser.getId(),item);
                sysRoleUsers.add(sysRoleUser);

            });
           return iSysRoleUserService.saveBatch(sysRoleUsers);
        }
        return false;
    }

}
